Skip to content

gh-155742: Use PyMem_Malloc() in memoryview.hex() - #158582

Merged
vstinner merged 1 commit into
python:mainfrom
vstinner:memoryview_hex
Oct 2, 2026
Merged

vstinner merged 1 commit into
python:mainfrom
vstinner:memoryview_hex

Conversation

@vstinner

@vstinner vstinner commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Replace PyBytesWriter with a simple PyMem_Malloc(), since no bytes object is needed. PyMem_Malloc() should be more efficient in this case.

Replace PyBytesWriter with a simple PyMem_Malloc(), since no bytes
object is needed. PyMem_Malloc() should be more efficient in this
case.
@vstinner

vstinner commented Oct 1, 2026

Copy link
Copy Markdown
Member Author

The function was modified in Python 3.15 to replace PyBytes_FromStringAndSize(NULL, size) with PyBytesWriter. I noticed later that no bytes object is needed, so a simple PyMem_Malloc() is enough.

Change similar to PR gh-157587 which replaced PyBytes_FromStringAndSize(NULL, size) with PyMem_Malloc(size).

Note: for simple views (ex: memoryview(bytes)), MV_C_CONTIGUOUS() code path is taken: no memory is copied, _Py_strhex_with_sep() is called directly on the view buffer.

cc @methane

@vstinner
vstinner merged commit b5aa195 into python:main Oct 2, 2026
59 checks passed
@vstinner
vstinner deleted the memoryview_hex branch October 2, 2026 15:51
@vstinner

vstinner commented Oct 2, 2026

Copy link
Copy Markdown
Member Author

Merged. Thanks for the review, I'm always more confident when a core dev can double check my change ;-)

I was a little bit worried that PyBuffer_ToContiguous() can modify src->len, but this function treats src as constant, so we are fine :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants